import axios from 'axios'
import {
  MessageBox,
  Message,
  Loading
} from 'element-ui'
import store from '@/store'
import {
  getToken,
  getUserData
} from '@/utils/auth'


let loading;
// const BASEURL = process.env.NODE_ENV === 'production' ? '' : 'http://121.36.60.34:8015'
const BASEURL =  process.env.VUE_APP_BASE_API
// console.log("BASEURL", process.env.NODE_ENV)
console.log("BASEURL",BASEURL)
// 创建axios实例
const service = axios.create({
  transformRequest: [
    function (data) {
       let ret = ''
       for (let it in data) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
       }
       ret = ret.substring(0, ret.lastIndexOf('&'));
       return ret
    }
  ],
  baseURL: BASEURL, // url = base url + request url
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // 跨域请求时发送cookie
  timeout: 5000, // 请求超时
})


// 请求拦截器
service.interceptors.request.use(
  config => {
    // 在发送请求之前做一些事情
    if (store.getters.token) {
      //请根据实际情况修改
      // config.headers['X-Token'] = getToken()//token加入到请求头中
      config.data['token'] = getToken() //token加入到请求参数中
      config.data['user_data'] = getUserData() //user_data加入到请求参数中
    }
    if (!config.data['noloading']) {
      startLoading();
    }
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    return config
  },
  error => {
    endLoading();
    //处理请求错误
    console.log('error',error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  /**
   *如果您想获取http信息，如标题或状态
   * Please return  response => response
   */

  /**
   *通过自定义代码确定请求状态
   *这里只是一个例子
   *您还可以通过HTTP状态代码判断状态
   */
  response => {

    endLoading();
    const res = response.data
    // console.log('res',res)
    // if the custom code is not 20000, it is judged as an error.
    // if (res.code !== 20000) {

      if (response.status === 401 ) {

          MessageBox.alert('登录状态已过期，请重新登录',
          '系统提示').then(() => {
                store.dispatch('user/resetToken').then(() => {
                  location.reload() //为了重新实例化vue-router对象 避免bug
                })
          })

      }
      else if(response.status==404 || response.status>500)
      {
        Message({
          message: res.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
      }
      else if(response.status==200 )
      {


        if (res.statecode !== 0) {
          // Message({
          //   message: res.message || 'Error',
          //   type: 'error',
          //   duration: 5 * 1000
          // })
          MessageBox.alert(res.message,'提示')
          return Promise.reject(new Error(res.message || 'Error'))
        }
        else {
           return res
        }
      }

  },
  error => {
    endLoading();
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

function startLoading() {
  // element-ui loading 服务调用方式
  loading = Loading.service({
    lock: true,
    text: '拼命加载中...',
    spinner: 'el-icon-loading', // 自定义图标
    background: 'rgba(0, 0, 0, 0.7)'
  })
}

// loading结束 方法
function endLoading() {
  loading.close()
}



export default service
